from collections import OrderedDict

import numpy as np

from ch4.numerical_diff import numerical_gradient
from ch5.Affine import Affine
from ch5.Relu import Relu
from ch5.soft_max_with_loss import SoftmaxWithLoss


class TwoLayerNet:

    def __init__(self, input_size, hidden_size, output_size, weight_init_std=0.01):
        """
        初始化权重
        :param input_size: 输入的维度
        :param hidden_size:隐藏的维度，不是层数。（一层有多少个神经元）
        :param output_size: 输出的维度
        :param weight_init_std:
        """
        self.params = {}
        self.params['W1'] = weight_init_std * np.random.randn(input_size, hidden_size)
        self.params['b1'] = np.zeros(hidden_size)
        self.params['W2'] = weight_init_std * np.random.randn(hidden_size, output_size)
        self.params['b2'] = np.zeros(output_size)

        self.layers = OrderedDict()
        self.layers['Affine1'] = Affine(self.params['W1'], self.params['b1'])
        self.layers['Relu1'] = Relu()
        self.layers['Affine2'] = Affine(self.params['W2'], self.params['b2'])
        self.lastLayer = SoftmaxWithLoss()

    def predict(self, x):
        """
        前向推导过程。
        :param x: 初始化输入
        :return:
        """
        for layer in self.layers.values():
            x = layer.forward(x)
        return x

    def loss(self, x, t):
        """
        损失函数。首先执行前向推导，随后计算误差
        :param x: 输入矩阵
        :param t: 真实的结果,独热表示。（监督数据）
        :return: 交叉熵函数，是一个值。
        """
        y = self.predict(x)
        return self.lastLayer.forward(y, t)

    def accuracy(self, x, t):
        """
        计算精度。
        假如，x是100*784，y是100*10。
        :param x: 输入的矩阵参数
        :param t: 正确的结果矩阵
        :return:
        """
        y = self.predict(x)
        y = np.argmax(y, axis=1)  # 此时的y是一个一维数组，有100个元素
        if t.ndim != 1: t = np.argmax(t, axis=1)
        accuracy = np.sum(y == t) / float(x.shape[0])  # x.shape[0]是100
        return accuracy

    def numerical_gradient(self, x, t):
        """
        数值微分，求梯度。
        这个过程包括了前向推到以及误差的求解。
        计算完误差后，利用误差对权重求偏导
        :param x:输入数据
        :param t:监督数据
        :return:
        """
        loss_W = lambda W: self.loss(x, t)
        grads = {}
        grads['W1'] = numerical_gradient(loss_W, self.params['W1'])
        grads['b1'] = numerical_gradient(loss_W, self.params['b1'])
        grads['W2'] = numerical_gradient(loss_W, self.params['W2'])
        grads['b2'] = numerical_gradient(loss_W, self.params['b2'])
        return grads

    def gradient(self, x, t):
        """
        利用反向传播，求梯度
        :param x:
        :param t:
        :return:
        """
        # 前向推导
        self.loss(x, t)
        # 反向传播
        dout = 1
        dout = self.lastLayer.backward(dout)
        layers = list(self.layers.values())
        layers.reverse()  # 逆转
        for layer in layers:
            dout = layer.backward(dout)
        # 设定
        grads = {}
        grads['W1'] = self.layers['Affine1'].dW
        grads['b1'] = self.layers['Affine1'].db
        grads['W2'] = self.layers['Affine2'].dW
        grads['b2'] = self.layers['Affine2'].db
        return grads


if __name__ == '__main__':
    net = TwoLayerNet(input_size=784, hidden_size=100, output_size=10)
    x = np.random.randn(100, 784)
    y = net.predict(x)
    print(y.shape)
